package com.pf.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Map;

/**
 * 邮件工具类
 *
 * @author PF
 * @date 2021/6/24 20:35
 * @Version 1.0
 */
@Component
@Slf4j
public class MailUtils {

    static {
        /**
         * 邮件附件文件名长度如果大于60并且splitLongParameters的值为true，encodeParameters的值为true，文件名就会被截取。
         * 因此可设置该值为false，这样邮件附件名称就不会被截取
         */
        System.setProperty("mail.mime.splitlongparameters", "false");
    }

    /**
     * 邮件发送人
     */
    @Value("${spring.mail.username}")
    private String sender;


    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 使用thymeleaf模板发送邮件
     */
    @Autowired
    private TemplateEngine templateEngine;


    /**
     * 发送thymeleaf模板邮件
     *
     * @param toUsers      接收人
     * @param ccUsers      抄送人
     * @param subject      邮件主体
     * @param data         模板数据
     * @param templateName 模板名称
     */
    public void sendTemplateThymeleaf(List<String> toUsers, List<String> ccUsers, String subject, Map<String, Object> data, String templateName) {
        if (sender == null || toUsers == null || subject == null) {
            log.error("MailUtils sendTemplateThymeleaf param error!");
            return;
        }
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            // 发送人
            messageHelper.setFrom(sender);
            // 接收人
            messageHelper.setTo(toUsers.toArray(new String[toUsers.size()]));
            // 抄送人
            if (ccUsers != null) {
                messageHelper.setCc(ccUsers.toArray(new String[ccUsers.size()]));
            }
            // 邮件标题
            messageHelper.setSubject(subject);

            //使用模板thymeleaf
            Context context = new Context();
            // 定义模板数据
            context.setVariables(data);
            //获取thymeleaf的html模板
            String emailContent = templateEngine.process(templateName, context);
            messageHelper.setText(emailContent, true);

            // 发送邮件
            javaMailSender.send(mimeMessage);
            log.info("thymeleaf模板邮件发送成功...");
        } catch (Exception e) {
            log.error("MailUtils sendTemplateThymeleaf error", e);
            throw new RuntimeException("邮件发送失败！");
        }
    }


}
